package com.haidechizi.i18n.interceptor;

import com.haidechizi.i18n.common.config.Configuration;
import com.haidechizi.i18n.common.execute.wapper.TranslateExecuteProxy;
import com.haidechizi.i18n.common.utils.GlobalUtils;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 国际化的切面
 */
@Slf4j
public class I18nInterceptor implements MethodInterceptor {

    @Autowired
    private TranslateExecuteProxy translateExecuteProxy;

    @Autowired
    private Configuration configuration;

    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        Object model = methodInvocation.proceed();
        try {
            // 判断是否跳过国际化翻译
            String translate = GlobalUtils.getTranslate();
            if ("false".equals(translate)) {
                return model;
            }
            if (configuration.getDefaultLanguage().equals(GlobalUtils.getLanguage())) {
                log.debug("language won't be translate! lang:{}", GlobalUtils.getLanguage());
                return model;
            }
            // 进行国际化
            translateExecuteProxy.assembleI18nInfo(model);
        } catch (Throwable e) {
            log.warn("国际化出现异常", e);
        }
        return model;
    }
}
